package com.cangjie.xiaozhi

import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.ui.content.ContentFactory
import com.intellij.ui.jcef.JBCefBrowser
import java.awt.BorderLayout
import java.awt.FlowLayout
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import javax.swing.JButton
import javax.swing.JPanel

class XiaozhiToolWindowFactory : ToolWindowFactory {
    companion object {
        const val XIAOZHI_URL = "https://yuanbao.tencent.com/bot/app/agent/cmmKveGl8ACU"
    }
    
    override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
        val myToolWindow = XiaozhiToolWindow()
        val content = ContentFactory.getInstance().createContent(myToolWindow.getContent(), "", false)
        toolWindow.contentManager.addContent(content)

        // 将实例存储到项目服务中，以便其他地方可以访问
        XiaozhiToolWindowService.getInstance().setToolWindow(myToolWindow)
    }
}

class XiaozhiToolWindow : Disposable {
    private lateinit var panel: JPanel
    private lateinit var browser: JBCefBrowser
    private var pageLoaded = false
    private val loadingLatch = CountDownLatch(1)
    
    init {
        createUI()
    }
    
    private fun createUI() {
        panel = JPanel(BorderLayout())
        
        // 创建包含工具栏和浏览器的主面板
        val mainPanel = JPanel(BorderLayout())
        
        // 创建工具栏面板
        val toolbarPanel = createToolbarPanel()
        mainPanel.add(toolbarPanel, BorderLayout.NORTH)
        
        // 创建浏览器
        browser = JBCefBrowser(XiaozhiToolWindowFactory.XIAOZHI_URL)
        
        // 添加页面加载完成的监听器
        browser.jbCefClient.addLoadHandler(object : org.cef.handler.CefLoadHandlerAdapter() {
            override fun onLoadingStateChange(browser: org.cef.browser.CefBrowser?, isLoading: Boolean, canGoBack: Boolean, canGoForward: Boolean) {
                if (!isLoading) {
                    pageLoaded = true
                    loadingLatch.countDown()
                    println("页面加载状态改变完成")
                }
            }
            
            override fun onLoadEnd(p0: org.cef.browser.CefBrowser?, p1: org.cef.browser.CefFrame?, p2: Int) {
                pageLoaded = true
                loadingLatch.countDown()
                println("页面加载结束，状态码: $p2")
                
                // 通过CSS隐藏指定的元素
                val hideElementsScript = """
                    (function() {
                        // 创建样式元素
                        var style = document.createElement('style');
                        style.type = 'text/css';
                        // hide nav icon && download app icon
                        style.innerHTML = `
                            div.yb-common-nav-fixed {
                                display: none !important;
                            }
                            div.agent-dialogue__tool__download {
                                display: none !important;
                            }
                        `;
                        // 将样式添加到页面头部
                        document.head.appendChild(style);
                    })();
                """.trimIndent()
                
                browser.cefBrowser.executeJavaScript(hideElementsScript, browser.cefBrowser.url, 0)
            }
        }, browser.cefBrowser)
        
        mainPanel.add(browser.component, BorderLayout.CENTER)
        panel.add(mainPanel, BorderLayout.CENTER)
    }
    
    private fun createToolbarPanel(): JPanel {
        val toolbarPanel = JPanel(FlowLayout(FlowLayout.LEFT))
        val refreshButton = JButton("刷新")
        refreshButton.addActionListener {
            refreshPage()
        }
        toolbarPanel.add(refreshButton)
        return toolbarPanel
    }
    
    fun getContent(): JPanel {
        return panel
    }
    
    fun waitForPageLoad(timeoutSeconds: Long = 10): Boolean {
        println("开始等待页面加载，超时时间: ${timeoutSeconds}秒")
        return try {
            val result = loadingLatch.await(timeoutSeconds, TimeUnit.SECONDS)
            println("等待页面加载结果: $result, pageLoaded状态: $pageLoaded")
            result && pageLoaded
        } catch (e: InterruptedException) {
            println("等待页面加载被中断: ${e.message}")
            false
        }
    }
    
    fun refreshPage() {
        println("刷新页面")
        browser.cefBrowser.reload()
    }
    
    fun sendMessageToEditor(message: String) {
        println("准备发送消息到编辑器，消息内容: $message")
        // 使用JavaScript将消息发送到页面的div.ql-editor元素
        // 将多行内容用<p>标签封装
        val lines = message.split("\n")
        val htmlContent = lines.joinToString("") { line ->
            "<p>${line.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")}</p>"
        }
        
        val script = """
            (function() {
                console.log("开始执行JavaScript代码");
                var interval = setInterval(function() {
                    var editor = document.querySelector('div.ql-editor');
                    if (editor) {
                        console.log("找到编辑器元素");
                        clearInterval(interval);
                        editor.innerHTML = '';
                        // 添加多行内容
                        var htmlContent = `${htmlContent}`;
                        editor.innerHTML = htmlContent;
                        // 触发input事件，让编辑器意识到内容变化
                        var inputEvent = new Event('input', { bubbles: true });
                        editor.dispatchEvent(inputEvent);
                        console.log("消息已发送到编辑器");
                    } else {
                        console.log("未找到编辑器元素");
                    }
                }, 500);
                // 最多重试10次
                setTimeout(function() {
                    clearInterval(interval);
                    console.log("停止尝试发送消息");
                }, 5000);
            })();
        """.trimIndent()
        browser.cefBrowser.executeJavaScript(script, browser.cefBrowser.url, 0)
        println("JavaScript代码已提交执行")
    }
    
    override fun dispose() {
        if (::browser.isInitialized) {
            Disposer.dispose(browser)
        }
    }
}